package com.nemo.fenxiangs.controller;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.nemo.fenxiangs.po.ItemsCustom;
import com.nemo.fenxiangs.po.QueryItemsVo;
import com.nemo.fenxiangs.service.ItemsService;
import com.nemo.fenxiangs.validation.ValidGroup1;

@Controller
//为了对url进行分类管理，可以在这里定义根路径、最终访问url是根路径+子路径
@RequestMapping("/items")
public class ItemsController {
	@Autowired
	private ItemsService itemsService;
	
	// 商品分类
	//itemtypes表示最终将方法返回值放在request中的key
	@ModelAttribute("itemtypes")
	public Map<String, String> getItemTypes() {

		Map<String, String> itemTypes = new HashMap<String, String>();
		itemTypes.put("智能访客系统","智能访客系统");
		itemTypes.put("出租车管理系统","出租车管理系统");
		itemTypes.put("自助终端产品","自助终端产品");
		itemTypes.put("标准化菜市场","标准化菜市场");
		itemTypes.put("护理通讯系统","护理通讯系统");
		return itemTypes;
	}

	//添加商品
	@RequestMapping("/addItemsSubmit")
	public String addItems(QueryItemsVo queryItemsVo,
			MultipartFile pic1,
			MultipartFile pic2) throws Exception{
		//原文件名称
		String pictureFile_name = pic1.getOriginalFilename();
		if(pic1!=null && pictureFile_name!=null &&pictureFile_name.length()>0){
			queryItemsVo.getItems().setPic1(saveFile(pic1));	
		}
		
		 pictureFile_name = pic2.getOriginalFilename();
		if(pic2!=null && pictureFile_name!=null &&pictureFile_name.length()>0){
			queryItemsVo.getItems().setPic2(saveFile(pic2));
		}
		
		itemsService.insertItems(queryItemsVo);
		return "success";
	}
	
	/*
	 * 保存文件
	 * */
	public String saveFile( MultipartFile pictureFile) throws IllegalStateException, IOException{
		//原文件名称
		String pictureFile_name = pictureFile.getOriginalFilename();
		if(pictureFile!=null && pictureFile_name!=null &&pictureFile_name.length()>0){
			
		//新文件名称
		String newFileName= UUID.randomUUID().toString()+
				pictureFile_name.substring(pictureFile_name.indexOf("."));
		//上传图片
		File uploadPic = new File("E:/websoft/fenxiangs/images/"+newFileName);
		
		if(!uploadPic.exists()){
			uploadPic.mkdirs();
		}
		//向磁盘写入文件
		pictureFile.transferTo(uploadPic);
		return newFileName;
		}
		return null;
	}
	
	
	//后台商品查询
	@RequestMapping(value={"/queryItems"},method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView queryItems( HttpServletRequest request,QueryItemsVo queryItemsVo,Integer pageNow) throws Exception{
		
		Integer productsCount =itemsService.getProductsCount(queryItemsVo);
		queryItemsVo.setTotalCount(productsCount);
		String producttype2="";
		 String name2 ="";
		 if(queryItemsVo.getItemsCustom()!=null){
			 producttype2 = queryItemsVo.getItemsCustom().getProducttype();
			 name2 =queryItemsVo.getItemsCustom().getName();
		 }
		 
		List<ItemsCustom>  itemsList = itemsService.findItemsList(queryItemsVo);
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("$totalPageCount",queryItemsVo.getTotalPageCount());
		modelAndView.addObject("$pageNow",pageNow);
		if(producttype2!=null){modelAndView.addObject("$producttype",producttype2);}
		if(name2!=null){modelAndView.addObject("$name",name2);}
		 modelAndView.addObject("itemsList", itemsList);
		 modelAndView.setViewName("items/itemsList");
		 return modelAndView;
	}
	//前台商品查询
	@RequestMapping(value="/showItems",method={RequestMethod.GET,RequestMethod.POST})
	public ModelAndView showItems(HttpServletRequest request,QueryItemsVo queryItemsVo,Integer pageNow) throws Exception{
		
		Integer productsCount =(int)itemsService.getProductsCount(queryItemsVo);
		queryItemsVo.setTotalCount(productsCount);
		List<ItemsCustom>  itemsList = itemsService.findItemsList(queryItemsVo);
		ModelAndView modelAndView = new ModelAndView();
		String $producttype = "";
		if( queryItemsVo.getItemsCustom()!=null){$producttype= queryItemsVo.getItemsCustom().getProducttype();}	
		if($producttype!=null){ modelAndView.addObject("$producttype", $producttype);}
		modelAndView.addObject("$totalPageCount",queryItemsVo.getTotalPageCount());
		modelAndView.addObject("$pageNow",pageNow);
		modelAndView.addObject("itemsList", itemsList);
		modelAndView.setViewName("items/itemsShow");
		return modelAndView;
	} 
			
	//转到商品修改页面
	@RequestMapping(value="/editItems",method={RequestMethod.GET,RequestMethod.POST})
	public String editItems(Model model,@RequestParam(value="id",required=true) Integer items_id) throws Exception{
		ItemsCustom itemsCustom =itemsService.findItemsById(items_id);
//		if(itemsCustom == null){
//			throw new CustomException("您查询的商品信息不存在！");
//		}
		model.addAttribute("items",itemsCustom);
		return "items/editItems";
	}
	
	//商品修改提交
	//在需要检验的pojo前添加@Validated，在需要校验的pojo后添加BindingResult bindingResult这个参数接收检验错误提示信息
	//注意@Validated和BindingResult bindingResult是成对出现 ，参数顺序固定。
	//@ModelAttribute它可以指定pojo数据放入request域中的key
	@RequestMapping(value="editItemsSubmit" ,method={RequestMethod.GET,RequestMethod.POST})
	public String editItemsSubmit(Model model,
			Integer id,
			@ModelAttribute("items")@Validated(value={ValidGroup1.class}) ItemsCustom itemsCustom,
			BindingResult bindingResult,
			MultipartFile img1,
			MultipartFile img2) throws Exception{
		
		//原文件名称
		String pictureFile_name = img1.getOriginalFilename();
		if(img1!=null && pictureFile_name!=null &&pictureFile_name.length()>0){
			itemsCustom.setPic1( saveFile(img1));	
		}
		 pictureFile_name = img2.getOriginalFilename();
		if(img2!=null && pictureFile_name!=null &&pictureFile_name.length()>0){
			itemsCustom.setPic2(saveFile(img2));
		}
		itemsService.updateItems(id, itemsCustom);
		//重定向到商品列表页面
		return "success";
		//转发发商品列表页面
		//return "forward:queryItems.action";
	}
	
	//删除商品信息
	@RequestMapping(value="/deletItems",method={RequestMethod.GET,RequestMethod.POST})
	public String deletItems(Integer[] items_id) throws Exception{
		
			for (Integer integer : items_id) {
				itemsService.deleteByPrimaryKey(integer);
			}
		
			return "success";
	}
	
	//转到批量修改商品信息页面
	@RequestMapping(value="/editItemsQuery")
	public String editItemsAll(Integer[] items_id,Model model) throws Exception{
		List<ItemsCustom > itemsList=new ArrayList<ItemsCustom>();
		for (Integer integer : items_id) {
			itemsList.add(itemsService.findItemsById(integer));
		}
		model.addAttribute("itemsList", itemsList);
		return "items/editItemsQuery";
	}
	
	//批量商品修改提交
	@RequestMapping("/editItemsAllSubmit")
	public String editItemsAllSubmit(QueryItemsVo queryItemsVo) throws Exception{
		
		for (ItemsCustom itemsCustom :queryItemsVo.getItemsList()) {
			itemsService.updateItems(itemsCustom.getId(),itemsCustom);
		}
		return "redirect:queryItems.action";
	}
}
